<?php
/**
    De chay duoc doan controller nay can imp cac goi sau:
    1/Vendor/xmlparser/xexcelxmlparser
    2/Vendor/cryptastic
    3/plugin/file_upload (toan bo goi plugin nay DE UPLOAD 1 FILE, xem them tai: 
    http://bakery.cakephp.org/articles/webtechnick/2009/02/10/file-upload-component-w-automagic-model-optional
    
    http://www.mainelydesign.com/blog/view/importing-excel-file-into-cakephp
    Truoc khi chay can tao 1 table ghi_nhan_tai_lens, tao MVC cho bang nay
**/
/* ***************DEBUG**************************
 * ****Trong truong hop no bao loi 
  FileUpload: A file was detected, 
  but was unable to be processed due to a misconfiguration of FileUpload. 
  Current config -- fileModel:'Upload' fileVar:'file'
 * ***vo plugins/file_upload/config/file_upload_settings  sua o line 40
 'fileModel' => 'Khfile',
 
 
 ************Ph?n m? r?ng c?a t?p tin không h?p l?.
    FileUpload::processFile() - Unable to save temp file to file system
    ...\plugins\file_upload\config\file_upload_settings.php
 sua o :  'allowedTypes' => array(
 
 ___________sua thong bao loi ở plugins/vendors/uploader
 
 **/

App::import('Vendor', 'xmlparser/xexcelxmlparser');
App::import('Vendor', 'cryptastic');


error_reporting(E_ALL ^ E_NOTICE);
require_once 'readmains_controller.php';

class KhfilesController extends AppController {

	var $name = 'Khfiles';
    var $helpers = array('Html', 'Form', 'FileUpload.FileUpload');
    var $components = array('FileUpload.FileUpload');
    var $paginate=array('order'=>array('ngaytao'=>'desc'),'limit'=>10);
	
    function index() {
    
		$this->Khfile->recursive = 0;
		$this->set('khfiles', $this->paginate());
        
	}
    /**
     * Trang tim kiem
     * */
    function search(){
        
    }
    /**
     * hien thi ket qua tim kiem
     * */
    
    function kq() {
        $this->layout='ajax';
        if(!empty($this->data)){
            $ngaybd = date('Y-m-d',strtotime($this->data['Khfile']['ngaybd']));
            $ngaykt = date('Y-m-d',strtotime($this->data['Khfile']['ngaykt']));
            $this->set('khfiles', $this->Khfile->find('all',array(
                    'conditions'=>array('ngaytao between ? and ?'=>array($ngaybd,$ngaykt)))));
        }
        
	}
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid khfile', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('khfile', $this->Khfile->read(null, $id));
	}
	
  
   
	function add(){
    //set dinh dang ngay theo khu vuc
        date_default_timezone_set('UTC');
        ini_set('memory_limit','1024M'); 
        if(!empty($this->data)){
            //kiem tra loi rong?
            $er=$this->FileUpload->showErrors();
            
            if($this->FileUpload->success||empty($er)){ //if uploaded successfully or the error message is empty
                if(empty($this->data['Khfile'][0]['file']['name'])){
                      $this->Session->setFlash('Nội dung đã tạo thành công!', 'default', array('class' => 'success'));              
                      $this->redirect(array('action'=>'index'));                    
              
                }
                //luu ten cua tap tin vua up len
                $client_filename = $this->data['Khfile'][0]['file']['name'];            
             
                
                //dat lai ten tap tin khi dua no len server, de phong trung ten,
                //thiet lap chuoi de dat ten
                $server_filename =  '_'. date('s-m-hi-d-m-Y').str_replace(' ','_',$client_filename);                              
                
                
                //thong tin file vua dua len se ghi nhan lai
                $save_data ['Khfile'] ['tieude']=     $this->data['Khfile']['tieude'];
                $save_data ['Khfile'] ['noidung']=     $this->data['Khfile']['noidung'];
                $save_data['Khfile']['tenfile'] = $client_filename;
                $save_data['Khfile']['tenfileserver'] = $server_filename;
                $save_data['Khfile']['kieu'] = $this->data['Khfile'][0]['file']['type'];
                $save_data['Khfile']['dolon'] =$this->data['Khfile'][0]['file']['size'];               
                
                
                //doi ten file tap tin vua dua len
                @rename(WWW_ROOT.'files'.DS.$client_filename, WWW_ROOT.'files'.DS.$server_filename);
                
                //luu thong tin file vua upload
                if(!$this->Khfile->query("
                    insert into khfiles (tieude,noidung,tenfile,tenfileserver,kieu,nhanvien_id,donvi_id,dolon) values
                        ('".
                            $save_data['Khfile']['tieude']."','".
                            $save_data['Khfile']['noidung']."','".
                            $save_data['Khfile']['tenfile']."','".
                            $save_data['Khfile']['tenfileserver']."','".
                            $save_data['Khfile']['kieu']."','".
                            $this->Session->read('cur_manv')."','".
                            $this->Session->read('cur_dv')."','".                            
                            $save_data['Khfile']['dolon']."');" ) )
                {     
                    //neu k luu dc thi phai xoa file
                    @unlink(WWW_ROOT.DS.'files'.DS. $save_data['Khfile']['tenfileserver']);
	
                    $this->Session->setFlash('Loi luu tru tren server!');
                    $this->redirect(array('action'=>'index'));                    
                }
                
                //xoa nhung file vo dụng, k xac dinh duoc chu nhân
                $this->Khfile->query('delete from khfiles where nhanvien_id=0');
                $this->Session->setFlash('File được upload thành công!', 'default', array('class' => 'success'));              
                $this->redirect(array('action'=>'index'));                    
                
            }else{
  //              debug($this->FileUpload->showErrors());
  //hien thi loi neu co loi
                $this->Session->setFlash($er);
            }
        }
        
        $this->set('files');
    }   
/**
 * Khong chinh sua lai file dinh kem
 * */
	function edit($id = null) {
        if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Thông tin không tồn tại.', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Khfile->query("update khfiles set 
                        tieude='".$this->data ['Khfile']['tieude']."',
                        noidung='".$this->data ['Khfile']['noidung']."', ngaytao =CURRENT_TIMESTAMP() where id=".$id)) {
				$this->Session->setFlash(__('Thông tin đã được lưu', true), 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Thông tin không thể lưu.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Khfile->read(null, $id);
		}
        $this->set(compact('id'));
	}
    /**
     * Neu co chinh sua lai file dinh kem
     * */
    function editf($id = null){
         if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Thông tin không tồn tại.', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
		 $er=$this->FileUpload->showErrors();
            
            if($this->FileUpload->success||empty($er)){ //if uploaded successfully or the error message is empty
               
                //luu ten cua tap tin vua up len
                $client_filename = $this->data['Khfile'][0]['file']['name'];            
             
                
                //dat lai ten tap tin khi dua no len server, de phong trung ten,
                //thiet lap chuoi de dat ten
                $server_filename =  '_'. date('s-m-hi-d-m-Y').$client_filename;                              
                
                
                //thong tin file vua dua len se ghi nhan lai
                $save_data ['Khfile'] ['tieude']=     $this->data['Khfile']['tieude'];
                $save_data ['Khfile'] ['noidung']=     $this->data['Khfile']['noidung'];
                $save_data['Khfile']['tenfile'] = $client_filename;
                $save_data['Khfile']['tenfileserver'] = $server_filename;
                $save_data['Khfile']['kieu'] = $this->data['Khfile'][0]['file']['type'];
                $save_data['Khfile']['dolon'] =$this->data['Khfile'][0]['file']['size'];               
                
                //doi ten file tap tin vua dua len
                @rename(WWW_ROOT.'files'.DS.$client_filename, WWW_ROOT.'files'.DS.$server_filename);
                
                
                //lay ten cu de lat sau khi update xong thi xóa
                $tencu=$this->Khfile->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1,
                    'fields'=>array('tenfileserver')));
                
                
                //luu thong tin file vua upload
                if(!$this->Khfile->query("
                    update khfiles set tieude='".
                            $save_data['Khfile']['tieude']."', noidung='".
                            $save_data['Khfile']['noidung']."', tenfile='".
                            $save_data['Khfile']['tenfile']."', tenfileserver='".
                            $save_data['Khfile']['tenfileserver']."', kieu='".
                            $save_data['Khfile']['kieu']."',dolon='".                            
                            $save_data['Khfile']['dolon']."', ngaytao =CURRENT_TIMESTAMP() 	 where id=".$id ) )
                {     
                    //neu k luu dc thi phai xoa file
                    @unlink(WWW_ROOT.DS.'files'.DS. $save_data['Khfile']['tenfileserver']);
	
                    $this->Session->setFlash('Loi luu tru tren server!');
                    $this->redirect(array('action'=>'index'));                    
                }
                
                //xoa nhung file vo dụng, k xac dinh duoc chu nhân
                
                $this->Khfile->query('delete from khfiles where nhanvien_id=0');
                //xoa file cũ, đã bị thay thế bởi file mới upload lên
                @unlink(WWW_ROOT.DS.'files'.DS. $tencu ['Khfile'] ['tenfileserver']);
	
                $this->Session->setFlash('File được upload thành công!');
                $this->redirect(array('action'=>'index'));                    
                
            }else{
  //              debug($this->FileUpload->showErrors());
  //hien thi loi neu co loi
                $this->Session->setFlash($er);
            }
		}
		if (empty($this->data)) {
			$this->data = $this->Khfile->read(null, $id);
		}
        $this->set(compact('id'));
    }
	/**
 * Vua xoa thog tin trong csdl va trong webroot
 * */

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for khfile', true));
			$this->redirect(array('action'=>'index'));
		}
        
        $filexoa=$this->Khfile->find('first',array(
                'conditions'=>array('id'=>$id),
                'fields'=>array('tenfileserver'),
                'recursive'=>-1));
		if ($this->Khfile->delete($id)) {
			$this->Session->setFlash(__('File đã được xóa', true), 'default', array('class' => 'success'));
            //xoa file sau khi xoa trong csdl
            @unlink(WWW_ROOT.DS.'files'.DS.$filexoa ['Khfile'] ['tenfileserver']);
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Khfile was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
    /**
     * Hàm download file
     * */
    function download($id = null) {
        // get info about the file from DB with id
        $tenfile=$this->Khfile->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1,
                'fields'=>array('tenfileserver')));
        $tenfile=$tenfile ['Khfile'] ['tenfileserver'];
        if(empty($tenfile)){
            $this->Session->setFlash(__('Thông báo này không có tập tin đính kèm', true));
			$this->redirect(array('action'=>'index'));
        }
       // Configure::write('debug', 0);
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=".$tenfile);
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize(WWW_ROOT.DS.'files'.DS.$tenfile));
        readfile(WWW_ROOT.DS.'files'.DS.$tenfile);
        $fp = fopen(WWW_ROOT.DS.'files'.DS.$tenfile, "rb");
        fpassthru($fp);
        fclose($fp);
        
        $this->Session->setFlash(__('Download thành công!!'));                
        
        $this->redirect(array('action'=>'index'));
    } 
}
?>